<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use hehe\Trade;
use think\facade\Db;

/**
 * 直播列管理
 */
class Live extends Backend {
    /**
     * Live模型对象
     * @var object
     * @phpstan-var \app\admin\model\Live
     */
    protected object $model;
    protected object $goodsModel;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['id', 'anchor_name', 'user.username'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\admin\model\Live;
        $this->goodsModel = new \app\admin\model\goods\Goods;
    }


    /**
     * 删除直播
     */
    public function del(array $ids = []): void {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $where = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $pk = $this->model->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data = $this->model->where($where)->select();
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                Db::name('live_order_temp')->where(['live_id' => $v->id])->delete();
                $count += $v->delete();

            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    /**
     * 生成直播
     */
    public function generateLive() {
        //        $this->success('已生成直播，请选择您接下来的操作');
        $param = $this->request->param();
        if (empty($param['user_id'])) $this->error('没有待生成的记录');

        $anchor_name = empty($param['anchor_name']) ? null : trim($param['anchor_name']);
        $live_time = empty($param['live_time']) ? null : trim($param['live_time']);
        $live_time = empty($live_time) ? null : strtotime($live_time);

        //        if (empty($param['anchor_name'])) $this->error('请输入主播名称');
        //        if (empty($param['live_time'])) $this->error('请选择直播时间');

        //        print_r($param);die;

        $temp = db::name('live_order_temp')->where(['user_id' => $param['user_id']])->whereNull('live_id')->find();
        if (!$temp) $this->error('没有待生成的记录');

        Db::startTrans();
        try {
            $insert_live = [ // 生成直播记录
                'live_number' => Trade::generateTradeNo(),
                'user_id' => $param['user_id'], // 用户ID
                'live_time' => $live_time, // 直播时间
                'anchor_name' => $anchor_name, // 主播名称
                'create_time' => $this->timestamp, // 创建时间
            ];

            $live_id = db::name('user_live')->insertGetId($insert_live);

            $update = [
                'live_id' => $live_id,
                'submit_time' => $this->timestamp
            ];
            $result = Db::name('live_order_temp')->where(['user_id' => $param['user_id']])->whereNull('live_id')->update($update);
            db::commit();
        } catch (\Exception $e) {
            db::rollback();
            $this->error($e->getMessage());
        }

        if ($result) {
            $this->success('已生成直播，请选择您接下来的操作');
        } else {
            $this->error();
        }
    }

    /**
     * 修改临时订单的数量
     */
    public function updateOrderTempNum() {
        $param = $this->request->param();
        $update = [
            'num' => $param['num'],
            'update_time' => $this->timestamp
        ];
        $result = db::name('live_order_temp')->where(['id' => $param['id']])->update($update);
        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }

    /**
     * 保存临时订单
     */
    public function saveOrderTemp() {
        $param = $this->request->param();
        db::startTrans();
        try {
            foreach ($param['ids'] as $val) {
                $row = db::name('live_order_temp')->where(['goods_id' => $val, 'user_id' => $param['user_id']])->whereNull('submit_time')->find();
                if ($row) continue;
                $goods_specs = db::name('goods_specs')->where(['goods_id' => $val])->find();
                $insert = [
                    'goods_id' => $val,
                    'user_id' => $param['user_id'],
                    'color' => $goods_specs['color'],
                    'create_time' => $this->timestamp
                ];
                $result = db::name('live_order_temp')->insert($insert);
            }
            db::commit();
        } catch (\Exception $e) {
            db::rollback();
            $this->error($e->getMessage());
        }

        if ($result) {
            $this->success();
        } else {
            $this->error();
        }
    }


    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        $this->withJoinTable = ['user'];
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            //            ->with(['user'])
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items();

        foreach($list as $val){
            $val->live_time = empty($val->live_time) ? '' : date('m月d日 H点', $val->live_time);
            $val->create_time = date('m-d/H:i', $val->create_time);
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }


    public function edit(): void {
        $id = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $param = $this->request->post();
            if (!$param) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $param = $this->excludeFields($param);

            $anchor_name = empty($param['anchor_name']) ? null : trim($param['anchor_name']);
            $live_time = empty($param['live_time']) ? null : trim($param['live_time']);
            $live_time = empty($live_time) ? null : strtotime($live_time);

            $data = [
                'anchor_name' => $anchor_name,
                'live_time' => $live_time
            ];

            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('edit');
                        $validate->check($param);
                    }
                }
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row['live_time'] = empty($row['live_time']) ? '' : date('Y-m-d H:i:s', $row['live_time']);
        $this->success('', [
            'row' => $row
        ]);
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */
}